package com.wang.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wang.dao.IBaseDao;
import com.wang.dao.IHandler;
import com.wang.domain.Student;
import com.wang.util.DBCPUtil;

public class StudentDaoImpl implements IBaseDao<Student> {
	private static final String TABLE = "student";
	private List<Student> getStudentQuery(ResultSet resultlist) throws SQLException {
		List<Student> arrayList = new ArrayList<Student>();
		while(resultlist.next()){
			Student studentUser = new Student();
			studentUser.setId(resultlist.getLong("id"));
			studentUser.setUsername(resultlist.getString("username"));
			studentUser.setPassword(resultlist.getString("password"));
			arrayList.add(studentUser);
		}
		return arrayList;
	}
	public Student findByName(String name){
		IHandler<Student> handler = (resultlist)->getStudentQuery(resultlist);
		List<Student> list = BaseDaoImpl.sqlQuery("select * from "+TABLE+" where username=?", handler, name);
		return list.isEmpty()?null:list.get(0);
	}

	@Override
	public Student findOne(Long id) {
		IHandler<Student> handler = (resultlist)->getStudentQuery(resultlist);
		List<Student> list = BaseDaoImpl.sqlQuery("select * from "+TABLE+" where id=?", handler, id);
		return list.isEmpty()?null:list.get(0);
	}

	@Override
	public List<Student> findAll() {
		IHandler<Student> handler = (resultlist)->getStudentQuery(resultlist);
		List<Student> list = BaseDaoImpl.sqlQuery("select * from "+TABLE, handler);
		return list;
	}

	@Override
	public Integer delete(Long id) {
		return BaseDaoImpl.sqlExecute("delete from "+TABLE+" where id = ?", id);
	}

	@Override
	public Integer update(Student t) {
		return BaseDaoImpl.sqlExecute("update "+TABLE+" set username = ?,password = ? where id = ?", t.getUsername(),t.getPassword(),t.getId());
	}

	@Override
	public Integer add(Student t) {
		return BaseDaoImpl.sqlExecute("insert into "+TABLE+" (username,password) values (?,?)", t.getUsername(),t.getPassword());
	}
}
